<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form ref="jobFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item :label="$t('sysJob.code')" prop="roleCode">
        <el-input
          v-model="form.roleCode"
          :placeholder="$t('sysJob.codeRequired')"
          clearable
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
      <el-form-item :label="$t('sysJob.name')" prop="roleName">
        <el-input
          v-model="form.roleName"
          :placeholder="$t('sysJob.nameRequired')"
          clearable
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
      <el-form-item :label="$t('sysJob.operatePerm')" prop="permCodes">
        <el-select
          v-model="form.moduleId"
          clearable
          :placeholder="$t('sysJob.moduleRequired')"
          style="width: 100%"
          @change="selModule"
        >
          <el-option
            v-for="item in moduleLists"
            :key="item.moduleId"
            :label="item.moduleName"
            :value="item.moduleId"
          />
        </el-select>
        <el-checkbox
          v-model="checkedAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckedAll"
        >
          {{ $t("sysJob.checkAll") }}/{{ $t("sysJob.checkNoAll") }}
        </el-checkbox>
        <el-table
          :data="permArray"
          row-key="resourceId"
          border
          :show-header="false"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="resourceName" width="180"></el-table-column>
          <el-table-column prop="resourceName">
            <template #default="scope">
              <el-checkbox-group
                v-model="form.permCodes"
                @change="handleChecked"
              >
                <el-checkbox
                  v-for="item in scope.row.perms"
                  :key="item.permId"
                  :label="item.permCode"
                >
                  {{ item.permName }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item :label="$t('sysJob.description')" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :autosize="{ minRows: 2 }"
          maxlength="200"
          show-word-limit
          :placeholder="$t('sysJob.descriptionRequired')"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, type PropType } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { type FormInstance, type FormRules, ElMessage } from "element-plus";
import { useUserStore } from "jmash-core";

import type { ResourcePerm } from "@/api/system/permission/types";
import { permissionApi } from "@/api/system/permission/index";

import type { JobFormReq, JobKey, JobUpdateReq } from "@/api/system/job/types";
import { jobApi } from "@/api/system/job/index";

import { moduleApi } from "@/api/system/module/index";

import { roleApi } from "@/api/system/role/index";
const jobFormRef = ref<FormInstance>();
const model = defineModel<boolean>();
let form = reactive<JobFormReq>({
  requestId: Math.random() * 10 + "",
  roleType: "job",
  updateMask: "roleCode,roleName,description",
});

// 校验编码的唯一性
const codeExistValidate = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error(t("sysJob.codeRequired")));
  } else {
    const query = {
      tenant: useUserStore().user.tenant,
      roleCode: value,
      addFlag: !(form as JobUpdateReq).roleId ? true : false,
      roleId: (form as JobUpdateReq).roleId,
    };
    roleApi.existRole(query).then(({ data }) => {
      if (data === true) {
        callback(new Error(t("sysRole.codeExist")));
      } else {
        callback();
      }
    });
  }
};

const rules = reactive<FormRules<JobFormReq>>({
  roleCode: [{ required: true, validator: codeExistValidate, trigger: "blur" }],
  roleName: [
    { required: true, message: t("sysJob.nameRequired"), trigger: "blur" },
  ],
});
let moduleLists = ref([] as any);
const checkedAll = ref(false);
const isIndeterminate = ref(false);
const permArray = ref();
let operButtonCode = ref([] as any); // 所有的操作按钮code
const emits = defineEmits(["refresh"]);
const props = defineProps({
  entityKey: {
    type: Object as PropType<JobKey>,
    default: () => {},
  },
});

const keys = Object.keys(props.entityKey);

const update = ref(keys.length >= 1);

if (update.value) {
  jobApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
  });
}

const submitForm = async () => {
  await jobFormRef.value?.validate((valid) => {
    if (valid) {
      if (update.value) {
        jobApi.update(form as JobUpdateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      } else {
        jobApi.create(form).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}

function queryPermData() {
  if (form.moduleId) {
    permissionApi.permlist(form.moduleId).then(({ data }) => {
      permArray.value = data.results;
      traverseTree(data.results);
    });
  }
}

function queryRoleData() {
  moduleApi.moduleList().then(({ data }) => {
    moduleLists.value = data.results;
  });
}

// 所属模块
function selModule() {
  queryPermData();
}

// 递归遍历操作权限
function traverseTree(node: ResourcePerm[]) {
  for (let i = 0; i < node.length; i++) {
    for (let z = 0; z < node[i].perms.length; z++) {
      operButtonCode.value.push(node[i].perms[z].permCode);
    }
    traverseTree(node[i].children);
  }
}

// 全选
function handleCheckedAll(val: any) {
  form.permCodes = val ? operButtonCode.value : [];
  isIndeterminate.value = false;
}

// 单独选
function handleChecked(val: any[]) {
  form.permCodes = val;
  const checkedNum = val.length;
  checkedAll.value = checkedNum === operButtonCode.value.length;
  isIndeterminate.value =
    checkedNum > 0 && checkedNum < operButtonCode.value.length;
}
queryPermData();
queryRoleData();
</script>
